package com.xyw.code.taobaokeapi.util;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Splitter;
import com.xyw.common.taobaokecommon.util.HttpUtil;
import jdk.nashorn.api.scripting.JSObject;
import jdk.nashorn.api.scripting.NashornScriptEngine;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 * User: xuyiwei
 * Date: 2020/8/5
 * Time: 下午2:16
 * Email: 1328312923@qq.com
 * 淘口令工具类
 **/
public class TbkUtil {

    private static Pattern webPattern = Pattern.compile("https://[\\S\\.]+[:\\d]?[/\\S]+\\??[\\S=\\S&?]+[^\u4e00-\u9fa5]");

    /**
     * 验证是否包含淘宝口令 并返回淘口令值
     * @param token
     * @return
     */
    public static String getTkl(String token) {
        String str = "";
        if(StringUtils.isBlank(token)){
            return "";
        }
        //验证11位随机字符串tr
        String rgex = "[a-zA-Z0-9]{11}";
        // 匹配的模式
        Pattern pattern = Pattern.compile(rgex);
        Matcher m = pattern.matcher(token);
        while (m.find()) {
            str = m.group(0);
            return str;
        }

        return "";
    }

    /**
     * 验证是否包含淘宝口令 并返回淘口令值
     * @param token
     * @return
     */
    public static Boolean isTkl(String token) {
        if(StringUtils.isBlank(token)){
            return false;
        }
        //验证11位随机字符串tr
        String rgex = "([\\p{Sc}])\\w{8,12}([\\p{Sc}])";
        Pattern r = Pattern.compile(rgex);
        Matcher m = r.matcher(token);
        if (m.find()) {
            return true;
        }
        return false;
    }

    /**
     * 根据token获得url
     * @param token
     * @return
     */
    public static String getUrlByToken(String token) {
        Matcher matcher = webPattern.matcher(token);
        StringBuffer buffer = new StringBuffer();
        while(matcher.find()){
            buffer.append(matcher.group());
        }
        return buffer.toString().trim();
    }

    /**
     * 根据手淘分析的链接获得真实url
     * @param token
     * @return
     */
    public static String getRealUrlByToken(String token) {
        Map<String,String> param = getParamByToken(token);
        return param.get("url");
    }

    /**
     * 根据手淘分析的链接获得商品id
     * @param token
     * @return
     */
    public static String getProductId(String token) {
        String url =  getRealUrlByToken(token);
        Map<String,String> urlParam = getUrlParam(url);
        return urlParam.get("id");
    }


    /**
     * 根据真实链接url获得该链接的参数
     * @param url
     * @return
     */
    public static Map<String,String> getUrlParam(String url) {
        Map<String,String> paramMap = new HashMap<>();
        if(StringUtils.isBlank(url)){
            return paramMap;
        }
        String[] urls = url.split("\\?");
        if(urls.length>1){
            String params = urls[1];
            System.out.println(params);
            String [] p = params.split("&");
            Map<String, String> split = Arrays.stream(p).collect(Collectors.toMap(k->{
                String[] keys = k.split("=");
                if(keys.length>0){
                    return keys[0];
                }else{
                    return "key";
                }
            },v->{
                String[] vals = v.split("=");
                if(vals.length>1){
                    return vals[1];
                }else{
                    return "value";
                }
            },(o1,o2)->o1));
            return split;
        }
        return new HashMap<>();
    }


    /**
     * 过滤参数值里面多余的属性和字段
     * @param data
     * @return
     */
    public static String trimParamValue(String data){
        if(StringUtils.isBlank(data)){
            return "";
        }
        data = data.trim().replaceAll( "\\\\",   "/").replaceAll("'","");
        if(data.contains(";")){
            data = data.substring(0,data.indexOf(";"));
        }
        return data;
    }

    /**
     * 根据手淘分享的链接得到参数
     * @param token
     * @return
     */
    public static Map<String,String> getParamByToken(String token){
        String url = getUrlByToken(token);
        if(StringUtils.isBlank(url)){
            return new HashMap<>();
        }
        String html =  HttpUtil.getRequest(url);
        Document doc = Jsoup.parse(html);
        /*取得script下面的JS变量*/
        Elements e = doc.getElementsByTag("script").eq(1);
        HashMap map = new HashMap();
        /*循环遍历script下面的JS变量*/
        for (Element element : e) {
            /*取得JS变量数组*/
            String[] data = element.data().toString().split("var");
            /*取得单个JS变量*/
            for(String variable : data){
                /*过滤variable为空的数据*/
                if(variable.contains("=")){
                    /*取到满足条件的JS变量*/
                    if(variable.contains("bizCode") || variable.contains("shortName") || variable.contains("url")){
                        String[]  kvp = variable.split("=");
                        /*取得JS变量存入map*/
                        if(!map.containsKey(kvp[0].trim())) {
                            //如果变量值是url则要单独处理
                            StringBuffer valueSb = new StringBuffer();
                            if(kvp.length>2){
                                for(int i=1;i<kvp.length;i++){
                                    valueSb.append(kvp[i]);
                                    if(i!=kvp.length-1){
                                        valueSb.append("=");
                                    }
                                }
                            }else{
                                valueSb.append(kvp[1].trim().substring(0, kvp[1].trim().length()-1).toString());
                            }
                            map.put(kvp[0].trim(),trimParamValue(valueSb.toString()));
                        }
                    }
                }
            }
        }
        return map;
    }
}
